package com.kefu.exam.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.common.context.KefuContext;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.util.JacksonUtil;
import com.kefu.exam.mapper.ExamCascadeJumpMapper;
import com.kefu.exam.mapper.ExamPaperSubjectMapper;
import com.kefu.exam.mapper.ExamSubjectMapper;
import com.kefu.exam.model.ExamCascadeJump;
import com.kefu.exam.model.ExamPaperSubject;
import com.kefu.exam.model.ExamSubject;
import com.kefu.exam.vo.AnswerUnit;
import com.kefu.exam.vo.ExamPaperInsertVo;
import com.kefu.exam.vo.ExamPaperUpdateVo;
import com.kefu.exam.vo.SubjectUnit;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.exam.mapper.ExamPaperMapper;
import com.kefu.exam.model.ExamPaper;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author xy
 * @date 2022/02/28
 */
@Service
public class ExamPaperService extends AbstractKefuService<ExamPaper> {
    @Resource
    protected ExamPaperMapper examPaperMapper;
    @Resource
    protected ExamSubjectMapper examSubjectMapper;
    @Resource
    protected ExamSubjectService examSubjectService;
    @Resource
    protected ExamPaperSubjectMapper examPaperSubjectMapper;
    @Resource
    protected ExamCascadeJumpMapper examCascadeJumpMapper;


    public String addPager(ExamPaperInsertVo examPaperVo) {
        //1. 判断考卷名是否重复
        List<ExamPaper> list = examPaperMapper.selectList(Wrappers.lambdaQuery(ExamPaper.class)
                .eq(ExamPaper::getPaperName, examPaperVo.getPaperName()).eq(ExamPaper::getTenantId, KefuContext.getKefuContext().getTenantId()));
        if (null != list && list.size() > 0) {
            throw BusinessException.msg("问卷名重复");
        }
        ExamPaper info = examPaperVo.convert();
        save(info);
        logger.info("添加问卷: [{}]", JacksonUtil.toString(info));
        return info.getPaperId();
    }


    public String deletePaper(String id) {
        // 1. 判断问卷是否存在
        ExamPaper info = examPaperMapper.selectByPrimaryKey(id);
        if (Objects.isNull(info)) {
            throw BusinessException.msg("问卷已经被删除");
        }
        // 2. 判断考卷下是否存在问卷试题
        List<ExamPaperSubject> list = examPaperSubjectMapper.selectList(Wrappers.lambdaQuery(ExamPaperSubject.class)
                .eq(ExamPaperSubject::getPaperId, id));
        if (null != list && list.size() > 0) {
            throw BusinessException.msg("问卷存在问题无法删除");
        }
        int i = examPaperMapper.deleteById(id);
        logger.info("删除问卷[{}]:{}", i, JacksonUtil.toString(info));
        //TODO 是否删除问卷的答题信息
        return id;
    }


    public String updatePaper(ExamPaperUpdateVo examPaperVo) {
        // 1. 判断更新的问卷名是否已经存在
        List<ExamPaper> list = examPaperMapper.selectList(Wrappers.lambdaQuery(ExamPaper.class)
                .eq(ExamPaper::getPaperName, examPaperVo.getPaperName()).eq(ExamPaper::getTenantId, KefuContext.getKefuContext().getTenantId()));
        if (null != list && list.size() > 0) {
            for (ExamPaper paper :
                    list) {
                if (!paper.getPaperId().equals(examPaperVo.getPaperId())) {
                    throw BusinessException.msg("问卷已经存在");
                }
            }
        }
        ExamPaper info = examPaperVo.convert();
        int i = examPaperMapper.updateByPrimaryKey(info);
        logger.info("更新问卷信息[{}]:{}", i, JacksonUtil.toString(info));
        return info.getPaperId();
    }


    public Map<String, Object> findByIdAndSort(String paperId) {
        // 1. 查询试卷下的试题
        List<ExamPaperSubject> list = examPaperSubjectMapper.selectList(Wrappers.lambdaQuery(ExamPaperSubject.class)
                .eq(ExamPaperSubject::getPaperId, paperId)
                .orderByAsc(true, ExamPaperSubject::getSort)
        );
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ExamPaperSubject", list);
        if (null != list && list.size() > 0) {
            List<ExamSubject> examSubjects = Lists.newArrayList();
            for (ExamPaperSubject examPaperSubject :
                    list) {
                ExamSubject subject = examSubjectService.getById(examPaperSubject.getSubjectId());
                examSubjects.add(subject);
            }
            hashMap.put("ExamSubject", examSubjects);
        }

        return hashMap;
    }


    public ExamPaper findById(String id) {
        ExamPaper info = super.findById(id);
        // 1. 查询试卷下的试题
        List<ExamPaperSubject> list = examPaperSubjectMapper.selectList(Wrappers.lambdaQuery(ExamPaperSubject.class)
                .eq(ExamPaperSubject::getPaperId, id).orderByAsc(true, ExamPaperSubject::getSort));
        List<ExamCascadeJump> examCascadeJumpList = examCascadeJumpMapper.selectList(Wrappers.lambdaQuery(ExamCascadeJump.class)
                .eq(ExamCascadeJump::getTenantId, KefuContext.getKefuContext().getTenantId())
                .eq(ExamCascadeJump::getPaperId, id));
        if (null != list && list.size() > 0) {
            List<SubjectUnit> subjectUnitList = Lists.newArrayList();
            for (ExamPaperSubject paperSubject : list) {
                SubjectUnit subjectUnit = examSubjectService.getSubjectUnit(paperSubject.getSubjectId());
                for (ExamCascadeJump cascadeJump : examCascadeJumpList) {
                    if (subjectUnit.getSubject().getSubjectId().equals(cascadeJump.getSubjectId())) {
                        for (AnswerUnit answerUnit : subjectUnit.getAnswers()) {
                            if (answerUnit.getAnswer().getAnswerId().equals(cascadeJump.getAnswerId())) {
                                for (ExamPaperSubject examPaperSubject : list) {
                                    if (examPaperSubject.getSubjectId().equals(cascadeJump.getJumpSubject())) {
                                        answerUnit.setJump(String.valueOf(examPaperSubject.getSort()));
                                    }
                                }
                            }
                        }
                    }
                    subjectUnit.getAnswers().forEach(answer -> {
                        answer.getSonSubjectList().forEach(sonsubject -> {
                            sonsubject.getAnswers().forEach(sonAnswer -> {
                                if (sonAnswer.getAnswer().getAnswerId().equals(cascadeJump.getAnswerId())) {
                                    list.forEach(examPaperSubject -> {
                                        if (examPaperSubject.getSubjectId().equals(cascadeJump.getJumpSubject())) {
                                            sonAnswer.setJump(String.valueOf(examPaperSubject.getSort()));
                                        }
                                    });
                                }
                            });
                        });
                    });
                }
                subjectUnitList.add(subjectUnit);
            }
            info.setSubjectUnitList(subjectUnitList);
        }
        return info;
    }
}
